package com.changpei.search.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.changpei.common.utils.BeanUtil;
import com.changpei.common.utils.FilePrefix;
import com.changpei.search.pojo.CommentIndex;
import com.changpei.search.pojo.ContentIndex;
import com.changpei.search.pojo.HomeIndex;
import com.changpei.search.pojo.UserIndex;
import com.changpei.search.service.CommentIndexService;
import com.changpei.search.service.ContentIndexService;
import com.changpei.search.service.HomeIndexService;
import com.changpei.search.service.UserIndexService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 *
 *
 * @author Way on 2021/9/3
 */
@Component
@Slf4j
public class MessageListener {

    @Autowired
    private ContentIndexService contentIndexService;

    @Autowired
    private CommentIndexService commentIndexService;

    @Autowired
    private UserIndexService userIndexService;

    @Autowired
    private HomeIndexService homeIndexService;

    private static final String IS_AVAILABLE_URL = "http";

    /**
     * 接收内容消息
     * @param message
     */
    @RabbitListener(queues = "${mq.queue.content}")
    public void handleContentMessage(Message message) {
        if (validMessage(message.getBody())) {
            ContentIndex object = JSON.parseObject(new String(message.getBody(), StandardCharsets.UTF_8), ContentIndex.class);
            ContentIndex target = contentIndexService.findById(object.getId());
            BeanUtils.copyProperties(object, target, BeanUtil.getNullPropertyNames(object));
            contentIndexService.update(target);

            HomeIndex homeIndex = homeIndexService.findById(object.getId());
            if (!ObjectUtils.isEmpty(homeIndex)) {
                BeanUtils.copyProperties(object, homeIndex, BeanUtil.getNullPropertyNames(object));
                homeIndexService.update(homeIndex);
            }

        } else {
            log.error("同步es评论信息失败");
        }
    }

    /**
     * 接收内容消息
     * @param message
     */
    @RabbitListener(queues = "${mq.queue.comment}")
    public void handleCommentMessage(Message message) {
        if (validMessage(message.getBody())) {
            try {
                String contentMsg = new String(message.getBody(), StandardCharsets.UTF_8);
                CommentIndex commentIndex = JSONObject.parseObject(contentMsg, CommentIndex.class);

                // 添加用户信息
                UserIndex userIndex = userIndexService.findById(commentIndex.getUserId());
                commentIndex.setNickName(userIndex.getNickName());
                if (userIndex.getAvatarUrl().contains(IS_AVAILABLE_URL)) {
                    commentIndex.setAvatarUrl(userIndex.getAvatarUrl());
                } else {
                    commentIndex.setAvatarUrl(FilePrefix.AVATAR_URL_PREFIX + userIndex.getAvatarUrl());
                }

                // 添加回复用户信息
                String withoutReplyId = "0";
                if ((!ObjectUtils.isEmpty(commentIndex.getReplyId())) && (!new Long(withoutReplyId).equals(commentIndex.getReplyId()))) {
                    UserIndex replyUser = userIndexService.findById(commentIndex.getReplyId());
                    JSONObject replyJsonObject = new JSONObject();
                    replyJsonObject.put("nickName", replyUser.getNickName());
                    if (replyUser.getAvatarUrl().contains(IS_AVAILABLE_URL)) {
                        replyJsonObject.put("avatarUrl", replyUser.getAvatarUrl());
                    } else {
                        replyJsonObject.put("avatarUrl", FilePrefix.AVATAR_URL_PREFIX + replyUser.getAvatarUrl());
                    }

                    commentIndex.setReply(replyJsonObject);
                }

                commentIndexService.save(commentIndex);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.error("同步es内容信息失败");
        }
    }

    /**
     * 用户修改
     */
    @RabbitListener(queues = "${mq.queue.userModify}")
    public void userModify(Message message) {
        if (validMessage(message.getBody())) {
            UserIndex tmpUser = JSONObject.parseObject(new String(message.getBody(), StandardCharsets.UTF_8), UserIndex.class);
            UserIndex userIndex = userIndexService.findById(tmpUser.getId());
            BeanUtils.copyProperties(tmpUser, userIndex, BeanUtil.getNullPropertyNames(tmpUser));
            if (StringUtils.isNotEmpty(userIndex.getAvatarUrl()) && !userIndex.getAvatarUrl().contains(IS_AVAILABLE_URL)) {
                userIndex.setAvatarUrl(FilePrefix.AVATAR_URL_PREFIX + userIndex.getAvatarUrl());
            }
            if (StringUtils.isNotEmpty(userIndex.getCoveredImg()) && !userIndex.getCoveredImg().contains(IS_AVAILABLE_URL)) {
                userIndex.setCoveredImg(FilePrefix.USER_COVERED_IMG_URL_PREFIX + userIndex.getCoveredImg());
            }
            userIndexService.update(userIndex);
        }
    }

    /**
     * 用户关注
     * @param message
     */
    @RabbitListener(queues = "${mq.queue.follow}")
    public void userFollow(Message message) {
        if (validMessage(message.getBody())) {
            List<UserIndex> userIndices = JSONArray.parseArray(new String(message.getBody(), StandardCharsets.UTF_8), UserIndex.class);
            userIndices.forEach(u -> {
                UserIndex userIndex = userIndexService.findById(u.getId());
                BeanUtils.copyProperties(u, userIndex, BeanUtil.getNullPropertyNames(u));
                userIndexService.update(userIndex);
            });
        }
    }

    @RabbitListener(queues = "${mq.queue.commentModify}")
    public void commentModify(Message message) {
        if (validMessage(message.getBody())) {
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            JSONObject object = JSONObject.parseObject(msg);
            String delIdsKey = "ids";
            if (object.containsKey(delIdsKey)) {
                // 删除
                JSONArray ids = object.getJSONArray("ids");
                if (!ids.isEmpty()) {
                    for (Object id : ids) {
                        commentIndexService.deleteById(Long.parseLong(id.toString()));
                    }
                }
            } else {
                // 修改
                CommentIndex tmp = JSONObject.parseObject(msg, CommentIndex.class);
                CommentIndex commentIndex = commentIndexService.findById(tmp.getId());
                BeanUtils.copyProperties(tmp, commentIndex, BeanUtil.getNullPropertyNames(tmp));
                commentIndexService.update(commentIndex);
            }
        }
    }

    private boolean validMessage(Object msg) {
        return !ObjectUtils.isEmpty(msg);
    }
}
